<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests\SaleIntentionSaveRequest;
use App\Models\SaleIntention;
use App\Models\Custom;
use App\Http\ErrCode;
use Auth;
use Excel;

class SaleIntentionController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $keyword = $request->get('keyword','');
        $status = $request->get('status',-1);
        $export = $request->get('export',0);

        $builder = SaleIntention::with('user','assignUser')->where([]);

        if(!empty($keyword)){
            $builder->where(function($q) use($keyword){
                $q->where('custom_name','like','%'.$keyword.'%')
                  ->orWhere('contact_name','like','%'.$keyword.'%')
                  ->orWhere('contact_mobile','like','%'.$keyword.'%')
                  ->orWhere('intention','like','%'.$keyword.'%');
            });
        }

        if($status == 1){
            $builder->where('assign_user_id','>',0);
        }elseif($status == 0){
            $builder->where('assign_user_id','=',0);
        }

        $builder->where(['user_id'=>Auth::user()->id]);

        $builder->orderBy('id','desc');

        if($export == 1){
            $list = $builder->get();
            //清空缓冲区
            ob_clean();
            Excel::create(date('YmdHis').'_导出结果', function($excel) use($list) {
                 $excel->sheet('Sheet1', function($sheet) use($list) {
                     $headers = ['客户名称','合作意向','联系人','联系电话','创建人','客户经理','创建时间'];
                     $sheet->row(1,$headers);
                     $row = 2;
                     foreach ($list as $model) {
                         $sheet->row($row++,[
                            $model->custom_name,
                            $model->intention,
                            $model->contact_name,
                            $model->contact_mobile,
                            $model->user->name,
                            $model->assignUser->name,
                            $model->created_at
                        ]);
                     }
                 });
            })->download('xls');
        }else{
            $pager = $this->build_pager_data($builder->paginate(10));
            return response()->json(json_success($pager));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(SaleIntentionSaveRequest $request)
    {
        $data = array_null_to_empty($request->only(['custom_name','contact_name','contact_mobile','origin','intention']));

        //检测是否已经存在
        $exist_cond = [
            'custom_name' => $data['custom_name']
        ];
        if($this->modelExist(SaleIntention::class,$exist_cond)){
            return json_error(ErrCode::RESOURCE_EXIST,'数据已经存在');
        }

        $model = new SaleIntention();
        $model->user_id = Auth::user()->id;
        $model->fill($data);
        $model->save();
        return response()->json(json_success(['id'=>$model->id]));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $model = SaleIntention::with('user','assignUser')->findOrFail($id);
        return response()->json(json_success($model));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(SaleIntentionSaveRequest $request, $id)
    {
        $data = array_filter($request->only(['custom_name','contact_name','contact_mobile','origin','intention']));

        $model = SaleIntention::findOrFail($id);

        //检测是否已经存在
        $exist_cond = [
            'custom_name' => $data['custom_name']
        ];
        if($this->modelExist(SaleIntention::class,$exist_cond,$model->id)){
            return json_error(ErrCode::RESOURCE_EXIST,'数据已经存在');
        }

        $model->update($data);
        return response()->json(json_success());
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $model = SaleIntention::findOrFail($id);
        $model->delete();
        return response()->json(json_success());
    }


    //指定客户经理开发客户
    public function assignUser(Request $request,$id)
    {
        $data = array_null_to_empty($request->only(['user_id']));
        $model = SaleIntention::findOrFail($id);
        $model->assign_user_id = $data['user_id'];
        $model->assign_date = date('Y-m-d H:i:s');
        $model->save();
        return response()->json(json_success());
    }


    public function customDevResult(Request $request,$id){
        $result = $request->get('result',0);
        $model = SaleIntention::findOrFail($id);
        //开发失败
        if($result == 0){
            $model->delete();
        }
        //开发成功
        if($result == 1){
            //自动创建一个客户信息
            $custom = new Custom();
            $custom->name = $model->custom_name;
            //状态正常
            $custom->status = 0;
            //客户满意度
            $custom->happy = 1;
            //客户信用度
            $custom->credit = 1;
            //指定客户经理
            $custom->user_id = $model->assign_user_id;
            //联系电话
            $custom->phone = $model->contact_mobile;
            $custom->save();

            $model->delete();
        }

        return response()->json(json_success());

    }
}
